package com.st.buy.cart.controller;

import com.st.buy.cart.service.CartService;
import com.st.buy.pojo.TbItem;
import com.st.buy.pojo.TbUser;
import com.st.buy.util.pojo.BuyResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * @author 张双虎
 */
@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    @RequestMapping("/cart/delete/{itemId}")
    public String deleteCart(@PathVariable long itemId,HttpServletRequest request){
        HashMap user = (HashMap) request.getAttribute("loginUser");
        cartService.deleteCart(new Long(user.get("id").toString()),itemId);
        //重定向到购物车列表
        return "redirect:/cart/cart";
    }

    @RequestMapping("/cart/update/num/{itemId}/{num}")
    @ResponseBody
    public BuyResult updateNum(@PathVariable long itemId,@PathVariable int num,HttpServletRequest request){
        HashMap user = (HashMap) request.getAttribute("loginUser");
        return cartService.updateCart(new Long(user.get("id").toString()),itemId,num);
    }

    @RequestMapping("/cart/cart")
    public String cartList(HttpServletRequest request, Model model){
        HashMap user = (HashMap) request.getAttribute("loginUser");
        List<TbItem> cartList = cartService.getCartList(new Long(user.get("id").toString()));
        //计算总价，修改商品的image属性
        long totalPrice = 0;
        for (TbItem item : cartList){
            totalPrice += item.getPrice() * item.getNum();
            //处理图片
            String img = item.getImage();
            if(StringUtils.isNoneBlank(img)) {
                String [] imgs = img.split(";");
                if(imgs!=null && img.length()>0){
                    img = imgs[0];
                    item.setImage(img);
                }
            }
        }
        model.addAttribute("cartList",cartList);
        model.addAttribute("totalPrice",totalPrice);
        return "cart";
    }

    @RequestMapping("/cart/add/{itemId}")
    public String cartAdd(@PathVariable long itemId, int num, HttpServletRequest request){
        HashMap user = (HashMap) request.getAttribute("loginUser");
        if(user==null){
            return null;
        }
        cartService.cartAdd(new Long(user.get("id").toString()),itemId,num);
        return "cartSuccess";
    }
}
